import { defineStore } from 'pinia'
import {
  reactive, ref, computed,
  type Ref, type ComputedRef
} from 'vue'
import { v4 as uuidv4 } from 'uuid';
import { type ITextDefaultProps } from '../defaultProps'

export interface IComponentData {
  props: any;
  id: string;
  name: string;
}

export interface IEditorProps {
  // 中间编辑器渲染的数组
  components: IComponentData[];
  // 正在编辑的元素的id
  currentElement: Ref<string, string>;
  addComponent: (props: IComponentData) => void;
  deleteComponent: (comp: IComponentData) => void;
  setActive: (currentId: string) => void;
  updateComponent: (val: { [key: string]: any }) => void;
  curActiveComponent: ComputedRef<IComponentData | undefined>
}

export const testComponents: IComponentData[] = [
  {
    id: uuidv4(), name: 'l-text', props: {
      text: 'hello1', fontSize: '20px', tag: 'h3', lineHeight: '2', textAlign: 'center', fontFamily: 'KaiTi', color: '#000000'
    }
  },
  { id: uuidv4(), name: 'l-text', props: { text: 'hello2', fontSize: '10px', color: 'red' } },
  {
    id: uuidv4(), name: 'l-text', props: {
      text: 'hello3', fontSize: '15px', color: 'blue', actionType: 'url', url: 'https://www.baidu.com'
    }
  }
]

export const useEditorStore = defineStore('editor', (): IEditorProps => {
  const components = reactive(testComponents)
  const currentElement = ref<string>('')
  const curActiveComponent = computed(() => components.find(item => item.id === currentElement.value))
  const addComponent = (data: IComponentData) => {
    components.push(data)
  }
  const deleteComponent = (comp: IComponentData) => {
    const idx = components.findIndex(item => item.id === comp.id)
    if (idx >= 0) {
      components.splice(idx, 1)
    }
  }
  const setActive = (currentId: string) => {
    currentElement.value = currentId
  }
  const updateComponent = ({ k, val }: any) => {
    const updateComp = components.find(item => item.id === currentElement.value)
    if (updateComp) {
      updateComp.props[k as keyof ITextDefaultProps] = val
    }
  }
  return {
    components,
    currentElement,
    addComponent,
    deleteComponent,
    setActive,
    curActiveComponent,
    updateComponent
  }
})
